package com.smmisia.wx.controller;

import com.smmisia.wx.handler.WxChatMsgFactory;
import com.smmisia.wx.handler.WxChatMsgHandler;
import com.smmisia.wx.utils.MessageUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.Objects;

@RestController
@Slf4j
public class CallBackController {

    private static final String token = "qweasdfdsas";

    private final String appId = "wx7b709546e002dbda";

    private final String appSecret = "6fe4507642a502cf628df4193e8cb1ee";

    private final String redirectUri = "http://29iwpu.natappfree.cc/wechat/callback";

    @Resource
    private WxChatMsgFactory wxChatMsgFactory;

    @GetMapping("/test")
    public String test(){
        return "ok";
    }

    @GetMapping("/wechat/qr")
    public String wxLoginPage() throws UnsupportedEncodingException {
        //https://open.weixin.qq.com/connect/oauth2/authorize?
        // appid=APPID
        // &redirect_uri=REDIRECT_URI
        // &response_type=code
        // &scope=SCOPE
        // &state=STATE
        // #wechat_redirect

        //https://open.weixin.qq.com/connect/oauth2/authorize?
        // appid=wx807d86fb6b3d4fd2&
        // redirect_uri=http%3A%2F%2Fdevelopers.weixin.qq.com
        // &response_type=code
        // &scope=snsapi_userinfo
        // &state=STATE
        // #wechat_redirect
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?" +
                "appid=" + appId +
                "&redirect_uri=" + redirectUri +
                "&response_type=code" +
                "&scope=snsapi_userinfo" +
                "state=123" +
                "#wechat_redirect";
        return "redirect:"+url;
    }

    /**
     * 获取用户消息回调
     * @return
     */
    @GetMapping("/wechat/callback")
    public String callback(@RequestParam("code") String code){
//    log.info("get请求参数验签:signature:{},timestamp:{},nonce:{},echostr:{},"
//            ,signature,timestamp,nonce,echostr);
//        String shaStr = SHA1.getSHA1(token, timestamp, nonce, "");
//        if(signature.equals(shaStr)){
//            return echostr;
//        }
        String tokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appId
                + "&secret=" + appSecret
                + "&code=" + code
                + "&grant_type=authorization_code";

        RestTemplate restTemplate = new RestTemplate();
        WeChatAccessTokenResponse response = restTemplate.getForObject(tokenUrl, WeChatAccessTokenResponse.class);

        if (response != null) {
            String userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + response.getAccessToken()
                    + "&openid=" + response.getOpenId();
            WeChatUserInfo userInfo = restTemplate.getForObject(userInfoUrl, WeChatUserInfo.class);
            log.info(String.valueOf(userInfo));
            return "userProfile";
        }

        return "error";
    }



    /**
     * 回调消息校验
     * @return
     */
    @PostMapping(value = "/wechat/callback",produces = "application/xml;charset=UTF-8")
    public String callbacks(@RequestBody String requestBody) throws InterruptedException {
        Map<String, String> messageMap = MessageUtil.parseXml(requestBody);
        String msgType = messageMap.get("MsgType");
        String event = messageMap.get("Event") == null ? "" : messageMap.get("Event");
        log.info("msgType:{},event:{}", msgType, event);

        StringBuilder sb = new StringBuilder();
        sb.append(msgType);
        if (!StringUtils.isEmpty(event)) {
            sb.append(".");
            sb.append(event);
        }
        String msgTypeKey = sb.toString();
        WxChatMsgHandler wxChatMsgHandler = wxChatMsgFactory.getHandlerByMsgType(msgTypeKey);
        if (Objects.isNull(wxChatMsgHandler)) {
            return "unknown";
        }
        String replyContent = wxChatMsgHandler.dealMsg(messageMap);
        log.info("replyContent:{}", replyContent);
        return replyContent;
    }


    static class WeChatAccessTokenResponse {
        private String accessToken;
        private String openId;

        public String getAccessToken() {
            return accessToken;
        }

        public void setAccessToken(String accessToken) {
            this.accessToken = accessToken;
        }

        public String getOpenId() {
            return openId;
        }

        public void setOpenId(String openId) {
            this.openId = openId;
        }
    }

    static class WeChatUserInfo {
        private String openId;
        private String nickname;
        private String sex;
        private String province;
        private String city;
        private String country;
        private String headimgurl;

        public String getOpenId() {
            return openId;
        }

        public void setOpenId(String openId) {
            this.openId = openId;
        }

        public String getNickname() {
            return nickname;
        }

        public void setNickname(String nickname) {
            this.nickname = nickname;
        }

        public String getSex() {
            return sex;
        }

        public void setSex(String sex) {
            this.sex = sex;
        }

        public String getProvince() {
            return province;
        }

        public void setProvince(String province) {
            this.province = province;
        }

        public String getCity() {
            return city;
        }

        public void setCity(String city) {
            this.city = city;
        }

        public String getCountry() {
            return country;
        }

        public void setCountry(String country) {
            this.country = country;
        }

        public String getHeadimgurl() {
            return headimgurl;
        }

        public void setHeadimgurl(String headimgurl) {
            this.headimgurl = headimgurl;
        }
    }
}